//
//  AFFRichTextExpression.m
//  AnyfishApp
//
//  Created by Bob Lee on 14-4-18.
//  Copyright (c) 2014年 Anyfish. All rights reserved.
//

#import "AFFRichTextExpression.h"
#import "UIImage+Orientation.h"

static NSString *space = @" ";

@interface AFFRichTextExpression() {
    NSTimer *drawTimer;
    UIImageView *imgV;
    UIImage *img;
}

@end

@implementation AFFRichTextExpression

- (id)init
{
    self = [super init];
    if (self) {
        self.textType = ERichTextType_Exp;
        self.isResponseTouch = NO;
    }
    return self;
}

- (BOOL)drawRunWithRect:(CGRect)rect
{
    // 这里单独处理下扩展用的图标，要缩小尺寸
//    NSDictionary *mDicEx = [AFFAppSettings getExpPlistInfo:kDicKey_Exp_Extend];
//    if(mDicEx && self.originalText && [mDicEx objectForKey:self.originalText]){
//        CGFloat padding = 0;
//        rect = CGRectMake(padding+rect.origin.x, padding+rect.origin.y, CGRectGetWidth(rect)-padding*2, CGRectGetHeight(rect)-padding*2);
//    }
//
//    if(IOS_VERSION>=9.0){
//        CGFloat padding = 4.0f;
//        rect = CGRectMake(padding+rect.origin.x, padding+rect.origin.y, CGRectGetWidth(rect)-padding*2, CGRectGetHeight(rect)-padding*2);
//    }
    
   
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIImage *image = [UIImage imageWithFileName:self.originalText];
    if (image) {
        CGContextDrawImage(context, rect, image.CGImage);
    }
    
    return YES;
}

- (BOOL)drawRunWithView:(UIView*)view rect:(CGRect)rect{
    if(imgV==nil){
        CGFloat padding = 0;
        NSDictionary *mDicEx = [AFFAppSettings getExpPlistInfo:kDicKey_Exp_Extend];
        if(mDicEx && self.originalText && [mDicEx objectForKey:self.originalText]){
            padding = -2.0;
        }
        
        rect = CGRectMake(rect.origin.x, rect.origin.y, CGRectGetWidth(rect)+padding*2, CGRectGetHeight(rect)+padding*2);
        
        if(CGRectGetHeight(rect)>self.originalFont.lineHeightUsed){
            rect.origin.y -= (CGRectGetHeight(rect)-self.originalFont.lineHeightUsed)/2;
        }
        
        imgV = [[UIImageView alloc] initWithFrame:rect];
        imgV.backgroundColor = kSetting.color_f8f8f8;
        imgV.contentMode = UIViewContentModeScaleAspectFit;
        imgV.userInteractionEnabled = NO;
    }
    
    [view addSubview:imgV];
    
    // lsb 2016-06-30 替换为使用bundle外图片
    img = [UIImage imageWithFileNameOutBundle:self.expFullName];
//    img = [UIImage imageWithFileName:self.originalText];
    if(![NSString isNilOrEmpty:self.colorReplace]){
        img = [img imageWithTintColor:[UIColor colorWithARGBString:self.colorReplace]];
    }
    
    if(![NSString isNilOrEmpty:self.orientation]){
        U32 type = [self.orientation intValue];
        if(type>0){
            img = type==1?[img flipVertical]:[img flipHorizontal];
        }
    }
    
    if([self.isDrawAsyc boolValue]){
        drawTimer = [NSTimer timerWithTimeInterval:0.05
                                            target:self
                                          selector:@selector(updateImage)
                                          userInfo:nil
                                           repeats:NO];
        // 这里要控制不影响主线程更新UI，即滑动等操作时阻塞timer
        [[NSRunLoop currentRunLoop] addTimer:drawTimer forMode:NSDefaultRunLoopMode];
    }else{
        [self updateImage];
    }
    return YES;
}

- (void)updateImage {
    if(imgV && [imgV superview]){
        imgV.backgroundColor = [UIColor clearColor];
        if(imgV.image==nil)
            imgV.image = img;
    }
}

- (NSString*)expFullName {
    return @"";
}

+ (NSString *)analyzeText:(NSString *)sourceText runsArray:(NSMutableArray **)expArr
{
    return [AFFRichTextExpression analyzeText:sourceText runsArray:expArr location:0];
}

/**
 * @function
 * 说明 解析显示文本中的表情字符,支持给出一段文本中得起始位置部分单独处理
 * @param sourceText 原始文本字符
 * @param expArr 存在的表情图片名称
 * @param location 从哪里开始
 
 * @return 替换了表情字符后的文本
 */
+ (NSString *)analyzeText:(NSString *)sourceText runsArray:(NSMutableArray **)expArr location:(NSInteger)location
{
    @autoreleasepool {
        NSRange range = [sourceText rangeOfString:@"[" options:NSBackwardsSearch];
        if(range.length<=0)
            return sourceText;
        
        NSString *markL = @"[";
        NSString *markR = @"]";
        NSMutableArray *stack = [[NSMutableArray alloc] init];
        NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:sourceText.length];
        
        NSDictionary *mDic = [AFFAppSettings getExpPlistInfo:kDicKey_Exp_Anyfish];
        NSDictionary *mDicEx = [AFFAppSettings getExpPlistInfo:kDicKey_Exp_Extend];
        
        //偏移索引 由于会把长度大于1的字符串替换成一个空白字符。这里要记录每次的偏移了索引。以便简历下一次替换的正确索引
        int offsetIndex = 0;
        NSInteger expCount = 0;
        for (int i = 0; i < sourceText.length; i++)
        {
            @autoreleasepool {
                NSString *s = [sourceText substringWithRange:NSMakeRange(i, 1)];
                
                if (([s isEqualToString:markL]) || ((stack.count > 0) && [stack[0] isEqualToString:markL]))
                {
                    if (([s isEqualToString:markL]) && ((stack.count > 0) && [stack[0] isEqualToString:markL]))
                    {
                        for (NSString *c in stack)
                        {
                            [newString appendString:c];
                        }
                        [stack removeAllObjects];
                    }
                    
                    [stack addObject:s];
                    
                    if ([s isEqualToString:markR] || (i == sourceText.length - 1))
                    {
                        NSMutableString *expStr = [[NSMutableString alloc] init];
                        NSMutableString *expStrEx = [[NSMutableString alloc] init];
                        for(int i=0;i<stack.count;i++){
                            [expStr appendString:stack[i]];
                            if(i>0&&i<stack.count-1){
                                [expStrEx appendString:stack[i]];
                            }
                        }
                        
                        NSString *key = expStr, *color = nil, *ori = nil;
                        // 解析是否携带了控制数据 图片带的key解释：[图片key,颜色,翻转方向]
                        NSArray *arrC = [expStrEx componentsSeparatedByString:@","];
                        if(arrC.count>1){
                            key = [NSString stringWithFormat:@"%@%@%@", @"[", arrC[0], @"]"];
                            color = arrC[1];
                            if(arrC.count>2){
                                ori = arrC[2];
                            }else {
                                if([color isPureInt]){
                                    ori = color;
                                    color = nil;
                                }
                            }
                        }
                        
                        NSArray *allKeys = [mDic allKeysForObject:key];
                        if(!allKeys||allKeys.count<=0){
                            allKeys = [mDicEx allKeysForObject:key];
                        }
                        
                        if (allKeys&&allKeys.count>0&&expCount<1000)
                        {
                            AFFRichTextExpression *expText = [[AFFRichTextExpression alloc] init];
                            expText.range = NSMakeRange(i + 1 - expStr.length - offsetIndex + location/*加上偏移位置*/, 1);
                            expText.originalText = [NSString stringWithString:[allKeys objectWithIndex:0]];
                            expText.colorReplace = color;
                            expText.orientation = ori;
                            [*expArr addObject:expText];
                            [newString appendString:space];
                            
                            offsetIndex += expStr.length - 1;
                            expCount ++;
                        }
                        else
                        {
                            [newString appendString:expStr];
                        }
                        
                        [stack removeAllObjects];
                    }
                }
                else
                {
                    [newString appendString:s];
                }
            }
        }
        
        return newString;
    }
}


@end
